package org.example.interfaces.exception;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.example.infrastructure.common.Constants;
import org.example.interfaces.web.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author liyishan
 * @date 2023/5/8 15:02
 * @apiNote
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);

    @SuppressWarnings("unchecked")
    @ExceptionHandler(Exception.class)
    public Result handler(Exception ex) {
        logger.error("全局异常", ex);
        // Param Validator
        // spring 方式级别的校验
        if (ex instanceof ConstraintViolationException) {
            Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) ex).getConstraintViolations();
            Map<Path, String> collect = constraintViolations.stream().collect(Collectors.toMap(ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage));
            return Result.errorResp(Constants.RESULT_TYPE_FAILURE, collect.toString());
        }
        //@RequestBody注解错误校验
        logger.error("服务器异常", ex);
        return Result.errorResp("服务器异常，请联系管理员");
    }
}
